package com.atguigu.ssyx.acl.utils;

import com.atguigu.ssyx.model.acl.Permission;

import java.util.ArrayList;
import java.util.List;

/**
 * @作者:胡树苑
 * @时间:2025/9/11 15:26
 */
public class PermissionHelper {

    public  static List<Permission> buildPermission(List<Permission> alllist){
        //创建最终数据封装集合list
        List<Permission> trees = new ArrayList<>();
        //遍历所有菜单list集合,得到第一层数据 pid
        for (Permission permission : alllist) {
            if(permission.getPid()==0){
                permission.setLevel(1);
                //调用方法,从第一层开始往下找
                trees.add(findChildren(permission,alllist));
            }
        }
        return trees;
    }
//递归往下找,找到子节点
    //permission上层子节点，从这里开始找
    //alllist所有菜单
    private static Permission findChildren(Permission permission, List<Permission> alllist) {
        permission.setChildren(new ArrayList<Permission>());
        //遍历alllist所有菜单数据
        //判断当前节点id=pid是否一样，封装，递归往下找
        for (Permission child : alllist) {
            if(child.getPid().longValue()==permission.getId().longValue()){
               int level = permission.getLevel()+1;
               child.setLevel(level);
               if(permission.getChildren()==null){
                   permission.setChildren(new ArrayList<>());
               }
               //封装下一层数据
               permission.getChildren().add(findChildren(child,alllist));
            }
        }
        return permission;
    }
}
